﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace IntegratedOnBordDebug.UDPCore
{
    public sealed class IOCPServerUDP
    {
        /// <summary>
        /// 监听Socket，用于接受客户端的连接请求
        /// </summary>
        public Socket listenSocket;

        private int _port = 0;
        /// <summary>服务监听端口
        /// 
        /// </summary>
        public int Port { get { return _port; } }

        /// <summary>
        /// 用于服务器执行的互斥同步对象
        /// </summary>
        private static Mutex mutex = new Mutex();

        /// <summary>
        /// 用于每个I/O Socket操作的缓冲区大小
        /// </summary>
        public int bufferSize;

        /// <summary>
        /// 服务器上连接的客户端总数
        /// </summary>
        public int numConnectedSockets;

        /// <summary>
        /// 服务器能接受的最大连接数量
        /// </summary>
        public int numConnections;

        /// <summary>
        /// 完成端口上进行投递所用的IoContext对象池
        /// </summary>
        public SAEAPool IoContextPool;

        /// <summary>
        /// 完成端口上进行投递所用的发送对象SEAE池
        /// </summary>
        public List<SEAESendPool> PoolSend;

        public delegate void OnProcessAcceptDelegate(SocketAsyncEventArgs e);
        /// <summary>SOCKET 连接事件
        /// 
        /// </summary>
        public event OnProcessAcceptDelegate OnProcessAccept;

        public delegate void OnProcessAcceptSocketErrorDelegate(Socket s, SocketException e);
        /// <summary>SOCKET 连接异常事件
        /// 
        /// </summary>
        public event OnProcessAcceptSocketErrorDelegate OnProcessAcceptSocketError;

        public delegate void OnProcessAcceptErrorDelegate(Exception e);
        /// <summary>SOCKET 连接处理异常事件
        /// 
        /// </summary>
        public event OnProcessAcceptErrorDelegate OnProcessAcceptError;

        public delegate void OnDenyAcceptDelegate(EndPoint e);
        /// <summary>SOCKET 连接事件
        /// 
        /// </summary>
        public event OnDenyAcceptDelegate OnDenyAccept;

        public delegate void OnProcessReceiveDelegate(SocketAsyncEventArgs e);
        /// <summary>SOCKET 接收数据事件
        /// 
        /// </summary>
        public event OnProcessReceiveDelegate OnProcessReceive;

        public delegate void OnProcessSendDelegate(SocketAsyncEventArgs e);
        /// <summary>SOCKET 数据发送事件
        /// 
        /// </summary>
        public event OnProcessSendDelegate OnProcessSend;

        //ProcessError
        public delegate void OnProcessErrorDelegate(SocketAsyncEventArgs e);
        /// <summary>SOCKET 数据处理异常事件
        /// 
        /// </summary>
        public event OnProcessErrorDelegate OnProcessError;

        public delegate void OnCloseSocketDelegate(SocketAsyncEventArgs e);
        /// <summary>SOCKET 数据处理异常事件
        /// 
        /// </summary>
        public event OnCloseSocketDelegate OnCloseSocket;


        /// <summary>
        /// 构造函数，建立一个未初始化的服务器实例
        /// </summary>
        /// <param name="numConnections">服务器的最大连接数据</param>
        /// <param name="bufferSize"></param>
        public IOCPServerUDP(int numConnections, int bufferSize)
        {
            this.numConnectedSockets = 0;
            this.numConnections = numConnections;
            this.bufferSize = bufferSize;

            this.IoContextPool = new SAEAPool();
            this.PoolSend = new List<SEAESendPool>();

            // 为IoContextPool预分配SocketAsyncEventArgs对象
            for (int i = 0; i < this.numConnections; i++)
            {
                SocketAsyncEventArgs ioContext = new SocketAsyncEventArgs();
                ioContext.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted);
                ioContext.SetBuffer(new byte[this.bufferSize], 0, this.bufferSize);

                // 将预分配的对象加入SocketAsyncEventArgs对象池中
                this.IoContextPool.Push(ioContext);
            }
        }



        /// <summary>
        /// 当Socket上的发送或接收请求被完成时，调用此函数
        /// </summary>
        /// <param name="sender">激发事件的对象</param>
        /// <param name="e">与发送或接收完成操作相关联的SocketAsyncEventArg对象</param>
        private void OnIOCompleted(object sender, SocketAsyncEventArgs e)
        {
            // Determine which type of operation just completed and call the associated handler.
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.Receive:
                    this.ProcessReceive(e);
                    break;
                case SocketAsyncOperation.Send:
                    this.ProcessSend(e);
                    break;
                default:
                    throw new ArgumentException("The last operation completed on the socket was not a receive or send");
            }
        }

        /// <summary>
        ///接收完成时处理函数
        /// </summary>
        /// <param name="e">与接收完成操作相关联的SocketAsyncEventArg对象</param>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            // 检查远程主机是否关闭连接
            if (e.BytesTransferred > 0)
            {
                if (e.SocketError == SocketError.Success)
                {
                    Socket s = (Socket)e.UserToken;
                    //判断所有需接收的数据是否已经完成
                    if (s.Available == 0)
                    {


                        //输出显示
                        //string outStr = String.Format("收到连接数据：{0}", Encoding.UTF8.GetString(e.Buffer));
                        //mainForm.Invoke(mainForm.setlistboxcallback, outStr);
                        try
                        {
                            if (OnProcessReceive != null)
                            {
                                OnProcessReceive(e);
                            }
                        }
                        catch (Exception)
                        {

                        }


                        //// 设置发送数据
                        //Array.Copy(e.Buffer, 0, e.Buffer, e.BytesTransferred, e.BytesTransferred);
                        //e.SetBuffer(e.Offset, e.BytesTransferred * 2);
                        //if (!s.SendAsync(e))        //投递发送请求，这个函数有可能同步发送出去，这时返回false，并且不会引发SocketAsyncEventArgs.Completed事件
                        //{
                        //    // 同步发送时处理发送完成事件
                        //    this.ProcessSend(e);
                        //}
                    }

                    if (!s.ReceiveAsync(e))    //为接收下一段数据，投递接收请求，这个函数有可能同步完成，这时返回false，并且不会引发SocketAsyncEventArgs.Completed事件
                    {
                        // 同步接收时处理接收完成事件
                        this.ProcessReceive(e);
                    }
                }
                else
                {
                    this.ProcessError(e);
                }
            }
            else
            {
                this.CloseClientSocket(e);
            }
        }

        /// <summary>
        ///主动给客户端发送数据
        /// </summary>
        /// <param name="e">与接收完成操作相关联的SocketAsyncEventArg对象</param>
        public bool SendToClient(string ip, byte[] sendData)
        {
            bool flag = false;
            SocketAsyncEventArgs e = null;

            if (IoContextPool.TryPop(out e))
            {
                if (e.SocketError == SocketError.Success)
                {
                    e.UserToken = listenSocket;
                    byte[] newbytes = new byte[sendData.Length];
                    Array.Copy(sendData, 0, newbytes, 0, sendData.Length);
                    e.SetBuffer(newbytes, 0, sendData.Length);
                    e.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), 80);
                    if (listenSocket.SendAsync(e) != false)
                    {
                        ProcessReceive(e);
                        flag = true;
                    }
                }
                else
                {
                    this.ProcessError(e);
                }
            }
            else
            {

            }
            return flag;
        }

        /// <summary>
        ///主动给客户端发送数据
        /// </summary>
        /// <param name="e">与接收完成操作相关联的SocketAsyncEventArg对象</param>
        public bool SendToClient(SocketAsyncEventArgs e, byte[] sendData)
        {
            bool flag = false;
            if (e.SocketError == SocketError.Success)
            {
                Socket s = (Socket)e.UserToken;
                SEAESendPool se = PoolSend.Find(x => x.IsOnAction == false);
                if (se == null)
                {
                    se = new SEAESendPool(s);
                    se.IsOnAction = true;
                    PoolSend.Add(se);
                }

                se.SAEA.UserToken = listenSocket;
                byte[] newbytes = new byte[sendData.Length];
                Array.Copy(sendData, 0, newbytes, 0, sendData.Length);
                se.SAEA.SetBuffer(newbytes, 0, sendData.Length);
                if (listenSocket.SendAsync(se.SAEA) != false)
                {
                    ProcessReceive(se.SAEA);
                    flag = true;
                }
            }
            else
            {
                this.ProcessError(e);
            }
            return flag;
        }

        /// <summary>
        /// 当Socket上的主动发发送被完成时，调用此函数
        /// </summary>
        /// <param name="sender">激发事件的对象</param>
        /// <param name="e">与发送完成操作相关联的SocketAsyncEventArg对象</param>
        private void Ase_Completed(object sender, SocketAsyncEventArgs e)
        {
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.Receive:
                    this.ProcessReceive(e);
                    break;
                case SocketAsyncOperation.Send:
                    this.ProcessSend(e);
                    break;
                default:
                    throw new ArgumentException("The last operation completed on the socket was not a receive or send");
            }
            //PoolSend.Remove((SEAESendPool)sender);
        }

        /// <summary>
        /// 发送完成时处理函数
        /// </summary>
        /// <param name="e">与发送完成操作相关联的SocketAsyncEventArg对象</param>
        private void ProcessSend(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                Socket s = (Socket)e.UserToken;

                //接收时根据接收的字节数收缩了缓冲区的大小，因此投递接收请求时，恢复缓冲区大小
                e.SetBuffer(0, bufferSize);
                //e.SetBuffer(new byte[bufferSize], 0, bufferSize);
                try
                {
                    if (OnProcessSend != null)
                    {
                        OnProcessSend(e);
                    }
                }
                catch (Exception)
                {

                }

                if (!s.ReceiveAsync(e))     //投递接收请求
                {
                    // 同步接收时处理接收完成事件
                    this.ProcessReceive(e);
                }
            }
            else
            {
                this.ProcessError(e);
            }
        }

        /// <summary>
        /// 处理socket错误
        /// </summary>
        /// <param name="e"></param>
        private void ProcessError(SocketAsyncEventArgs e)
        {
            Socket s = e.UserToken as Socket;
            IPEndPoint localEp = s.LocalEndPoint as IPEndPoint;

            this.CloseClientSocket(s, e);

            //string outStr = String.Format("套接字错误 {0}, IP {1}, 操作 {2}。", (int)e.SocketError, localEp, e.LastOperation);
            //mainForm.Invoke(mainForm.setlistboxcallback, outStr);
            try
            {
                if (OnProcessError != null)
                {
                    OnProcessError(e);
                }
            }
            catch (Exception)
            {

            }


            //Console.WriteLine("Socket error {0} on endpoint {1} during {2}.", (int)e.SocketError, localEp, e.LastOperation);
        }

        /// <summary>
        /// 关闭socket连接
        /// </summary>
        /// <param name="e">SocketAsyncEventArg associated with the completed send/receive operation.</param>
        private void CloseClientSocket(SocketAsyncEventArgs e)
        {
            Socket s = e.UserToken as Socket;
            this.CloseClientSocket(s, e);
        }

        private void CloseClientSocket(Socket s, SocketAsyncEventArgs e)
        {
            lock (this)
            {


                Interlocked.Decrement(ref this.numConnectedSockets);

                //将失联的DTU从列表中剔除
                this.IoContextPool.Pools.Remove(this.IoContextPool.Pools.Find(p => p.SocketArgs == e));

                // SocketAsyncEventArg 对象被释放，压入可重用队列。
                this.IoContextPool.Push(e);

                //string outStr = String.Format("客户 {0} 断开, 共有 {1} 个连接。", s.RemoteEndPoint.ToString(), this.numConnectedSockets);
                //mainForm.Invoke(mainForm.setlistboxcallback, outStr);
                try
                {
                    if (OnCloseSocket != null)
                    {
                        OnCloseSocket(e);
                    }
                }
                catch (Exception ex) { }

                //Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", this.numConnectedSockets);
                try
                {
                    s.Shutdown(SocketShutdown.Send);
                }
                catch (Exception)
                {
                    // Throw if client has closed, so it is not necessary to catch.
                }
                finally
                {
                    s.Close();
                }
            }
        }

        /// <summary>
        /// accept 操作完成时回调函数
        /// </summary>
        /// <param name="sender">Object who raised the event.</param>
        /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
        private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)
        {
            this.ProcessAccept(e);
        }

        /// <summary>
        /// 监听Socket接受处理
        /// </summary>
        /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            Socket s = e.AcceptSocket;
            if (s.Connected)
            {
                try
                {
                    SocketAsyncEventArgs ioContext;
                    this.IoContextPool.TryPop(out ioContext);
                    if (ioContext != null)
                    {
                        // 从接受的客户端连接中取数据配置ioContext

                        ioContext.UserToken = s;
                        ioContext.AcceptSocket = s;

                        Interlocked.Increment(ref this.numConnectedSockets);

                        ObjectDTU dtu = new ObjectDTU();
                        dtu.LoginTime = DateTime.Now;   //登陆时间
                        dtu.SocketArgs = ioContext;     //异步参数
                        dtu.IPString = s.RemoteEndPoint.ToString(); //客户端ip地址与端口
                        dtu.IsOnline = true;
                        this.IoContextPool.Pools.Add(dtu); //添加到DTU列表方便查询管理

                        //string outStr = String.Format("客户 {0} 连入, 共有 {1} 个连接。", s.RemoteEndPoint.ToString(), this.numConnectedSockets);
                        //mainForm.Invoke(mainForm.setlistboxcallback, outStr);
                        try
                        {
                            if (OnProcessAccept != null)
                            {
                                OnProcessAccept(ioContext);
                            }
                        }
                        catch (Exception)
                        {

                        }

                        if (!s.ReceiveAsync(ioContext))
                        {
                            this.ProcessReceive(ioContext);
                        }
                    }
                    else        //已经达到最大客户连接数量，在这接受连接，发送“连接已经达到最大数”，然后断开连接
                    {
                        s.Send(Encoding.Default.GetBytes("连接已经达到最大数!"));
                        string outStr = String.Format("连接已满，拒绝 {0} 的连接。", s.RemoteEndPoint);
                        //mainForm.Invoke(mainForm.setlistboxcallback, outStr);
                        try
                        {
                            if (OnDenyAccept != null)
                            {
                                OnDenyAccept(s.RemoteEndPoint);
                            }
                        }
                        catch (Exception)
                        {

                        }

                        s.Close();
                    }
                }
                catch (SocketException ex)
                {
                    Socket token = e.UserToken as Socket;
                    string outStr = String.Format("DTU {0} 连接出错, 异常信息： {1} 。", token.RemoteEndPoint, ex.ToString());
                    //mainForm.Invoke(mainForm.setlistboxcallback, outStr);
                    try
                    {
                        if (OnProcessAcceptSocketError != null)
                        {
                            OnProcessAcceptSocketError(token, ex);
                        }
                    }
                    catch (Exception)
                    {

                    }

                    //Console.WriteLine("Error when processing data received from {0}:\r\n{1}", token.RemoteEndPoint, ex.ToString());
                }
                catch (Exception ex)
                {
                    //mainForm.Invoke(mainForm.setlistboxcallback, "异常：" + ex.ToString());
                    try
                    {
                        if (OnProcessAcceptError != null)
                        {
                            OnProcessAcceptError(ex);
                        }
                    }
                    catch (Exception)
                    {

                    }

                }
                // 投递下一个接受请求
                this.StartAccept(e);
            }
        }

        /// <summary>
        /// 从客户端开始接受一个连接操作
        /// </summary>
        /// <param name="acceptEventArg">The context object to use when issuing 
        /// the accept operation on the server's listening socket.</param>
        private void StartAccept(SocketAsyncEventArgs acceptEventArg)
        {
            if (acceptEventArg == null)
            {
                acceptEventArg = new SocketAsyncEventArgs();
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted);
            }
            else
            {
                // 重用前进行对象清理
                acceptEventArg.AcceptSocket = null;
            }

            if (!listenSocket.AcceptAsync(acceptEventArg))
            {
                ProcessAccept(acceptEventArg);
            }
        }

        /// <summary>
        /// 启动服务，开始监听
        /// </summary>
        /// <param name="port">Port where the server will listen for connection requests.</param>
        public void Start(int port)
        {
            // 获得主机相关信息
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
            Start(addressList[addressList.Length - 1], port);
        }

        public void Start(IPAddress IPA, int port)
        {
            _port = port;
            IPEndPoint localEndPoint = new IPEndPoint(IPA, port);

            // 创建监听socket
            listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
            listenSocket.ReceiveBufferSize = this.bufferSize;
            listenSocket.SendBufferSize = this.bufferSize;

            if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
            {
                // 配置监听socket为 dual-mode (IPv4 & IPv6) 
                // 27 is equivalent to IPV6_V6ONLY socket option in the winsock snippet below,
                listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
                listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
            }
            else
            {
                listenSocket.Bind(localEndPoint);
            }

            // 开始监听
            //listenSocket.Listen(this.numConnections);

            // 在监听Socket上投递一个接受请求。
            //StartAccept(null);

            // Blocks the current thread to receive incoming messages.
            mutex.WaitOne();
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        public void Stop()
        {
            if (this.listenSocket != null)
            {
                for (int i = 0; i < IoContextPool.Pools.Count; i++)
                {
                    SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
                    Socket s = IoContextPool.Pools[i].SocketArgs.UserToken as Socket;
                    s.DisconnectAsync(saea);
                }

                this.listenSocket.Close();
                this.listenSocket.Dispose();
            }
            mutex.ReleaseMutex();
        }
    }
}
